<template>
  <div class="plan-entry bg-background text-foreground p-4">
    <h2 class="text-2xl font-bold mb-4">园区应急预案管理</h2>


    <!-- Search Bar -->
    <div class="bg-card text-card-foreground p-4 mb-4 rounded shadow">
      <QueryForm :model="search" :formItems="formItems" @search="searchPlans" @reset="resetSearch" />
    </div>

    <!-- Action Buttons -->
    <div class="mb-4 space-x-2">
      <el-button type="primary" @click="openAddDialog">录入</el-button>
      <el-button type="danger" @click="deleteSelected">删除</el-button>
      <el-button @click="openImportDialog">导入</el-button>
      <el-button @click="exportData(planData, '预案管理', selectedIds)">导出</el-button>
    </div>

    <!-- Data Table -->
    <div class="bg-card text-card-foreground my-6 rounded shadow-md">
      <el-table v-loading="loading" :data="displayedPlanData" @selection-change="handleSelectionChange"
        style="width: 100%" ref="table" align="center" class="data-table" :header-cell-style="headerCellStyle"
        :row-key="rowKey">
        <el-table-column type="selection" width="55" :reserve-selection="true"></el-table-column>
        <el-table-column prop="EMERGENCE_PLAN_ID" label="预案编码" header-align="center" align="center"></el-table-column>
        <el-table-column prop="PARK_CODE" label="园区编码" header-align="center" align="center"></el-table-column>
        <el-table-column prop="COMPANY_CODE" label="企业编码" header-align="center" align="center"></el-table-column>
        <el-table-column prop="AREA_CODE" label="行政区划" header-align="center" align="center"></el-table-column>
        <el-table-column prop="EMERGENCE_PLAN_NAME" label="预案名称" header-align="center" align="center"></el-table-column>
        <el-table-column prop="EMERGENCE_PLAN_TYPE" label="预案类别" header-align="center" align="center"></el-table-column>
        <el-table-column prop="EMERGENCE_PLAN_LEVEL" label="预案等级" header-align="center" align="center"></el-table-column>
        <el-table-column prop="PREPARATION_DEPARTMENT" label="编制单位" header-align="center"
          align="center"></el-table-column>
        <el-table-column prop="RECORDED_RECENTLY_DATE" label="最近备案日期" header-align="center" align="center">
          <template #default="scope">
            <div>{{ dayjs(scope.row.RECORDED_RECENTLY_DATE).format('YYYY-MM-DD') }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="PLAN_REVIEWED_STATE" label="预案评估状态" header-align="center" align="center">
          <template #default="scope">
            <div>{{ scope.row.PLAN_REVIEWED_STATE == 1 ? '有效' : '超期' }}</div>
          </template>
        </el-table-column>
        <el-table-column label="操作" header-align="center" align="center">
          <template #default="scope">
            <el-button type="primary" size="small" @click="openEditDialog(scope.row)" link>编辑</el-button>
            <el-button type="primary" size="small" @click="viewDetails(scope.row)" link>查看</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- Pagination -->
    <Pagination v-if="planData.length" :tableData="planData" @alltabledata="alltabledata" />
    <!-- Add Plan Dialog -->
    <el-dialog width="1000px" class="dialog-from" v-model="isAddDialogOpen" :title="isEditing ? '编辑申请' : '新增申请'"
      destroy-on-close align-center :before-close="closeAddDialog">
      <form>
        <!-- 基本信息 -->
        <div>
          <div class="tablename">
            <div
              style="width: 10px; height: 10px; background-color:rgba(2, 125, 180, 1);margin-right: 10px;border:1px solid;">
            </div>
            <span>基本信息</span>
          </div>
          <div class="grid grid-cols-5 gap-6">
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">预案编码：</label>
              <el-input type="text" v-model="newRecord.EMERGENCE_PLAN_ID" required />
            </div>
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">园区编码：</label>
              <el-input type="text" v-model="newRecord.PARK_CODE" required />
            </div>
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">企业编码：</label>
              <el-input type="text" v-model="newRecord.COMPANY_CODE" required />
            </div>
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">行政区划：</label>
              <el-select v-model="newRecord.AREA_CODE" placeholder="请选择" clearable>
                <el-option label="大荔县" value="大荔县" />
              </el-select>
            </div>
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">编制单位：</label>
              <el-input type="text" v-model="newRecord.PREPARATION_DEPARTMENT" />
            </div>
            <!--  -->
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">预案名称：</label>
              <el-input type="text" v-model="newRecord.EMERGENCE_PLAN_NAME" required />
            </div>
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">预案类别：</label>
              <el-select v-model="newRecord.EMERGENCE_PLAN_TYPE" placeholder="请选择" clearable>
                <el-option label="综合应急预案" value="综合应急预案" />
                <el-option label="专项应急预案" value="专项应急预案" />
                <el-option label="现场处置方案" value="现场处置方案" />
                <el-option label="特殊时期/重大活动应急预案" value="特殊时期/重大活动应急预案" />
              </el-select>
            </div>
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">预案等级：</label>
              <el-select v-model="newRecord.EMERGENCE_PLAN_LEVEL" placeholder="请选择" clearable>
                <el-option label="上级应急预案" value="上级应急预案" />
                <el-option label="园区级应急预案" value="园区级应急预案" />
                <el-option label="企业级应急预案" value="企业级应急预案" />
              </el-select>
            </div>
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">预案评审日期：</label>
              <input type="date" v-model="newRecord.PLAN_REVIEW_DATE" required class="datetime" />
            </div>
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">预案评审意见：</label>
              <el-input type="text" v-model="newRecord.PLAN_REVIEW_COMMENTS" required />
            </div>
            <!--  -->
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">风险是否告知周边单位：</label>
              <el-select v-model="newRecord.RISK_HAS_TOLD_YES_OR_NO" placeholder="请选择" clearable>
                <el-option label="是" value="1" />
                <el-option label="否" value="0" />
              </el-select>
            </div>
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">风险告知周边的其他单位资料：</label>
              <!-- <el-input type="text" v-model="newRecord.RISK_HAS_TOLD_MATERIAL" /> -->
              <div v-if="isEditing" style="margin:10px 0">
                <div>
                  {{ newRecord.RISK_HAS_TOLD_MATERIAL }}
                </div>
                <el-button style="width: 75px; height: 30px;"
                  @click="uploadfile(apiBaseUrl + '/download/' + newRecord.RISK_HAS_TOLD_MATERIAL)">
                  下载查看

                </el-button>
              </div>
              <input type="file" id="importFile" @change="handleRISK_HAS" accept=".csv, .xlsx" class="mt-1 block w-full">
            </div>
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">初次发布日期：</label>
              <input type="date" v-model="newRecord.PUBLISHED_FIRST_TIME_DATE" class="datetime" />
            </div>
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">初次备案日期：</label>
              <input type="date" v-model="newRecord.RECORD_FIRST_TIME_DATE" class="datetime" />
            </div>
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">备案部门：</label>
              <el-input type="text" v-model="newRecord.RECORD_DEPART" required />
            </div>
            <!--  -->
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">备案部门性质：</label>
              <el-select v-model="newRecord.RECORD_DEPART_NATURE" placeholder="请选择" clearable>
                <el-option label="应急" value="应急" />
                <el-option label="交通运输" value="交通运输" />
                <el-option label="其他" value="其他" />
              </el-select>
            </div>
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">预案备案登记资料：</label>
              <!-- <el-input type="text" v-model="newRecord.PLAN_TO_RECORD_MATERIAL" required /> -->
              <div v-if="isEditing" style="margin:10px 0">
                <div>
                  {{ newRecord.PLAN_TO_RECORD_MATERIAL }}
                </div>
                <el-button style="width: 75px; height: 30px;"
                  @click="uploadfile(apiBaseUrl + '/download/' + newRecord.PLAN_TO_RECORD_MATERIAL)">
                  下载查看
                </el-button>
              </div>
              <input type="file" id="importFile" @change="handleRECORDMATERIAL" accept=".csv, .xlsx"
                class="mt-1 block w-full">
            </div>
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">最近发布日期：</label>
              <input type="date" v-model="newRecord.PUBLISHED_RECENTLY_DATE" required class="datetime" />
            </div>
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">最近定期评估日期：</label>
              <input type="date" v-model="newRecord.REVIEWED_RECENTLY_DATE" class="datetime" />
            </div>
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">最近备案日期：</label>
              <input type="date" v-model="newRecord.RECORDED_RECENTLY_DATE" required class="datetime" />
            </div>
            <!--  -->
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">定期评估周期：</label>
              <input type="text" v-model="newRecord.REVIEWED_RECENTLY_CYCLE" class="datetime" />
            </div>
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">预案评估状态：</label>
              <el-select v-model="newRecord.PLAN_REVIEWED_STATE" placeholder="请选择" clearable>
                <el-option label="有效" value="1" />
                <el-option label="超时" value="0" />
              </el-select>
            </div>
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">评估意见：</label>
              <el-select v-model="newRecord.PLAN_REVIEWED_COMMENTS" placeholder="请选择" clearable>
                <el-option label="需要修订" value="需要修订" />
                <el-option label="不需要修订" value="不需要修订" />
              </el-select>
            </div>
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">修订状态：</label>
              <el-select v-model="newRecord.REVISE_STATE" placeholder="请选择" clearable>
                <el-option label="已修订" value="已修订" />
                <el-option label="未修订" value="未修订" />
              </el-select>
            </div>
            <div>
              <label for="staffCode" class="block text-sm font-medium text-muted-foreground">预案文件：</label>
              <div v-if="isEditing" style="margin:10px 0">
                <div>
                  {{ newRecord.PLAN_FILE }}
                </div>
                <el-button style="width: 75px; height: 30px;"
                  @click="uploadfile(apiBaseUrl + '/download/' + newRecord.PLAN_FILE)">
                  下载查看
                </el-button>
              </div>
              <input type="file" id="importFile" @change="handlePLANFILE" accept=".csv, .xlsx" class="mt-1 block w-full">
            </div>
          </div>
        </div>
        <hr style="margin:8px" />
        <div class="mt-6 flex justify-end space-x-2">
          <el-button type="primary" @click="addNewPlan" style="width: 75px; height: 30px;">确认</el-button>
          <el-button @click="closeAddDialog" style="width: 75px; height: 30px;">取消</el-button>

        </div>
      </form>
    </el-dialog>
    <!-- Import Dialog -->
    <el-dialog width="400px" class="dialog-from" v-model="isImportDialogOpen" title="导入" destroy-on-close align-center
      :before-close="closeImportDialog">
      <div class="mb-4">
        <label for="importFile" class="block text-sm font-medium">选择文件</label>
        <input type="file" id="importFile" @change="handleFileUpload" accept=".csv, .xlsx" class="mt-1 block w-full">
      </div>
      <div class="mt-4 flex justify-end space-x-2">
        <el-button @click="closeImportDialog"
          class="bg-secondary text-secondary-foreground px-4 py-2 rounded">取消</el-button>
        <el-button v-loading.fullscreen.lock="fullscreenLoading" @click="confirmImport"
          class="bg-accent text-accent-foreground px-4 py-2 rounded" type="primary">确认导入</el-button>
      </div>

    </el-dialog>
    <!-- View Details Dialog -->
    <el-dialog width="1000px" class="dialog-from" v-model="isViewDialogOpen" title="记录详情" destroy-on-close align-center
      :before-close="closeViewDialog">
      <div class="body-item">
        <div class="tablename">
          <div
            style="width: 10px; height: 10px; background-color:rgba(2, 125, 180, 1);margin-right: 10px;border:1px solid;">
          </div>
          <span>基本信息</span>
        </div>
        <div class="box-content">
          <el-row :gutter="20" style="justify-content: space-evenly;flex-wrap: nowrap;margin:10px 0">
            <el-col :span="4">
              <div>
                <span class="no-wrap">预案编码:</span>
                <span class="auto-wrap">{{ selectedItem.EMERGENCE_PLAN_ID }}</span>
              </div>
            </el-col>
            <el-col :span="4">
              <div>
                <span class="no-wrap">园区编码:</span>
                <span class="auto-wrap">{{ selectedItem.PARK_CODE }}</span>
              </div>
            </el-col>
            <el-col :span="4">
              <div>
                <span class="no-wrap">企业编码:</span>
                <span class="auto-wrap">{{ selectedItem.COMPANY_CODE }}</span>
              </div>
            </el-col>
            <el-col :span="4">
              <div>
                <span class="no-wrap">行政区划:</span>
                <span class="auto-wrap">{{ selectedItem.AREA_CODE }}</span>
              </div>
            </el-col>
            <el-col :span="4">
              <div>
                <span class="no-wrap">编制单位:</span>
                <span class="auto-wrap">{{ selectedItem.PREPARATION_DEPARTMENT }}</span>
              </div>
            </el-col>
          </el-row>
          <!--  -->
          <el-row :gutter="20" style="justify-content: space-evenly;flex-wrap: nowrap;margin:10px 0">
            <el-col :span="4">
              <div>
                <span class="no-wrap">预案名称:</span>
                <span class="auto-wrap">{{ selectedItem.EMERGENCE_PLAN_NAME }}</span>
              </div>
            </el-col>
            <el-col :span="4">
              <div>
                <span class="no-wrap">预案类别:</span>
                <span class="auto-wrap">{{ selectedItem.EMERGENCE_PLAN_TYPE }}</span>
              </div>
            </el-col>
            <el-col :span="4">
              <div>
                <span class="no-wrap">预案等级:</span>
                <span class="auto-wrap">{{ selectedItem.EMERGENCE_PLAN_LEVEL }}</span>
              </div>
            </el-col>
            <el-col :span="4">
              <div>
                <span class="no-wrap">预案评审日期:</span>
                <span class="auto-wrap">{{ dayjs(selectedItem.PLAN_REVIEW_DATE).format('YYYY-MM-DD') }}</span>
              </div>
            </el-col>
            <el-col :span="4">
              <div>
                <span class="no-wrap">预案评审意见:</span>
                <span class="auto-wrap">{{ selectedItem.PLAN_REVIEW_COMMENTS }}</span>
              </div>
            </el-col>
          </el-row>
          <!--  -->
          <el-row :gutter="20" style="justify-content: space-evenly;flex-wrap: nowrap;margin:10px 0">
            <el-col :span="4">
              <div>
                <span class="no-wrap">风险告知周边单位:</span>
                <span class="auto-wrap">{{ selectedItem.RISK_HAS_TOLD_YES_OR_NO == 1 ? '是' : '否' }}</span>

              </div>
            </el-col>
            <el-col :span="4">
              <div>
                <span class="no-wrap">风险告知周边单位文件:</span>
                <span class="auto-wrap">{{ selectedItem.RISK_HAS_TOLD_MATERIAL }}</span>
                <el-button style="width: 75px; height: 30px;"
                  @click="uploadfile(apiBaseUrl + '/download/' + selectedItem.RISK_HAS_TOLD_MATERIAL)">
                  下载查看
                </el-button>
              </div>
            </el-col>
            <el-col :span="4">
              <div>
                <span class="no-wrap">首次发布日期:</span>
                <span class="auto-wrap">{{ dayjs(selectedItem.PUBLISHED_FIRST_TIME_DATE).format('YYYY-MM-DD') }}</span>
              </div>
            </el-col>
            <el-col :span="4">
              <div>
                <span class="no-wrap">初次备案日期:</span>
                <span class="auto-wrap">{{ dayjs(selectedItem.RECORD_FIRST_TIME_DATE).format('YYYY-MM-DD') }}</span>
              </div>
            </el-col>
            <el-col :span="4">
              <div>
                <span class="no-wrap">备案部门:</span>
                <span class="auto-wrap">{{ selectedItem.RECORD_DEPART }}</span>
              </div>
            </el-col>
          </el-row>
          <!--  -->
          <el-row :gutter="20" style="justify-content: space-evenly;flex-wrap: nowrap;margin:10px 0">
            <el-col :span="4">
              <div>

                <span class="no-wrap">备案部门性质:</span>
                <span class="auto-wrap">{{ selectedItem.RECORD_DEPART_NATURE }}</span>
              </div>
            </el-col>
            <el-col :span="4">
              <div>
                <span class="no-wrap">预案备案登记资料:</span>
                <span class="auto-wrap">{{ selectedItem.PLAN_TO_RECORD_MATERIAL }}</span>
              </div>
            </el-col>
            <el-col :span="4">
              <div>
                <span class="no-wrap">最近发布日期:</span>
                <span class="auto-wrap">{{ dayjs(selectedItem.PUBLISHED_RECENTLY_DATE).format('YYYY-MM-DD') }}</span>
              </div>
            </el-col>
            <el-col :span="4">
              <div>
                <span class="no-wrap">最近定期评估日期:</span>
                <span class="auto-wrap">{{ dayjs(selectedItem.REVIEWED_RECENTLY_DATE).format('YYYY-MM-DD') }}</span>
              </div>
            </el-col>
            <el-col :span="4">
              <div>
                <span class="no-wrap">最近备案日期:</span>
                <span class="auto-wrap">{{ dayjs(selectedItem.RECORDED_RECENTLY_DATE).format('YYYY-MM-DD') }}</span>
              </div>
            </el-col>
          </el-row>
          <!--  -->
          <el-row :gutter="20" style="justify-content: space-evenly;flex-wrap: nowrap;margin:10px 0">
            <el-col :span="4">
              <div>
                <span class="no-wrap">定期评估周期:</span>
                <span class="auto-wrap">{{ selectedItem.REVIEWED_RECENTLY_CYCLE }}</span>
              </div>
            </el-col>
            <el-col :span="4">
              <div>
                <span class="no-wrap">预案评估状态:</span>
                <span class="auto-wrap">{{ selectedItem.PLAN_REVIEWED_STATE == 1 ? '有效' : '超时' }}</span>
              </div>
            </el-col>
            <el-col :span="4">
              <div>
                <span class="no-wrap">评估意见:</span>
                <span class="auto-wrap">{{ selectedItem.PLAN_REVIEWED_COMMENTS }}</span>
              </div>
            </el-col>
            <el-col :span="4">
              <div>
                <span class="no-wrap">修订状态:</span>
                <span class="auto-wrap">{{ selectedItem.REVISE_STATE }}</span>
              </div>
            </el-col>
            <el-col :span="4">
              <div>
                <span class="no-wrap">预案文件:</span>
                <span class="auto-wrap">{{ selectedItem.PLAN_FILE }}</span>
                <el-button style="width: 75px; height: 30px;"
                  @click="uploadfile(apiBaseUrl + '/download/' + selectedItem.PLAN_FILE)">
                  下载查看
                </el-button>
              </div>
            </el-col>
          </el-row>
        </div>
      </div>
      <!-- <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="addExpert">确认</el-button>
          <el-button @click="closeViewDialog">
            取消
          </el-button>
        </div>
      </template> -->
    </el-dialog>

  </div>
</template>

<script setup>
import { ref, computed, onMounted, getCurrentInstance } from 'vue'
import axios from 'axios'
import { dayjs, ElLoading } from "element-plus"
const { proxy } = getCurrentInstance()
import { exportData, uploadfile, checkval } from '#/utils/exportfile.js'
const apiBaseUrl = ref(proxy.$currentUrl + '/api/plan-entry')

// 搜索相
const search = ref({
  EMERGENCE_PLAN_ID: '',
  EMERGENCE_PLAN_NAME: '',
  EMERGENCE_PLAN_TYPE: ''
})
const formItems = ref([
  {
    label: '预案编码：:',
    model: 'EMERGENCE_PLAN_ID',
    type: 'input',
    placeholder: '请输入',
  },
  {
    label: '预案名称：',
    model: 'EMERGENCE_PLAN_NAME',
    type: 'input',
    placeholder: '请输入',
  },
  {
    label: '预案类别：',
    model: 'EMERGENCE_PLAN_TYPE',
    type: 'select',
    placeholder: '请选择',
    options: [
      { label: '综合应急预案', value: '综合应急预案' },
      { label: '专项应急预案', value: '专项应急预案' },
      { label: '现场处置方案', value: '现场处置方案' },
      { label: '特殊时期/重大活动应急预案', value: '特殊时期/重大活动应急预案' },
    ],
  },

])
// 数据相关
const isEditing = ref(false)
const planData = ref([])
const selectedIds = ref([])
const selectedItem = ref(null) // 添加这行
const loading = ref(false)
const handleSelectionChange = (selected) => {
  selectedIds.value = selected
}
const importFile = ref(null)
const rowKey = (row) => row.ID // 设置行的唯一标识
// 对话框状态
const isAddDialogOpen = ref(false)
const isImportDialogOpen = ref(false)
const isViewDialogOpen = ref(false) // 添加这行
const isEditDialogOpen = ref(false) // 添加这行
const table = ref()
// 新记录
const newRecord = ref({
  EMERGENCE_PLAN_ID: '', //预案编码
  PARK_CODE: '', //园区编码
  COMPANY_CODE: '', //企业编码
  AREA_CODE: '', //行政区划
  PREPARATION_DEPARTMENT: '', //编制单位

  EMERGENCE_PLAN_NAME: '', //预案名称
  EMERGENCE_PLAN_TYPE: '', //预案类别
  EMERGENCE_PLAN_LEVEL: '', //预案等级
  PLAN_REVIEW_DATE: '', //预案评审日期
  PLAN_REVIEW_COMMENTS: '', //预案评审意见

  RISK_HAS_TOLD_MATERIAL: '', //风险告知周边单位
  RISK_HAS_TOLD_YES_OR_NO: '', //风险告知周边单位文件
  PUBLISHED_FIRST_TIME_DATE: '', //首次发布日期
  RECORD_FIRST_TIME_DATE: '', //初次备案日期
  RECORD_DEPART: '', //备案部门


  RECORD_DEPART_NATURE: '', //备案部门性质
  PLAN_TO_RECORD_MATERIAL: '', //预案备案登记资料
  PUBLISHED_RECENTLY_DATE: '', //最近发布日期
  REVIEWED_RECENTLY_DATE: '', //最近定期评估日期
  RECORDED_RECENTLY_DATE: '', //最近备案日期
  REVIEWED_RECENTLY_CYCLE: '', //定期评估周期
  PLAN_REVIEWED_STATE: '', //预案评估状态  
  PLAN_REVIEWED_COMMENTS: '', //评估意见
  REVISE_STATE: '', //修订状态
  PLAN_FILE: '', //预案文件
  files: []
})

const displayedPlanData = ref([])
const alltabledata = (data) => {
  displayedPlanData.value = data

}
// API 调用函数
const searchPlans = async () => {
  displayedPlanData.value = []
  try {
    // loading.value = true
    const response = await axios.get(`${apiBaseUrl.value}/search`, { params: search.value })
    planData.value = response.data.map(equipment => ({ ...equipment, selected: false }))
    // loading.value = false
  } catch (error) {
    console.error('搜索预案记录失败:', error)
    alert('搜索预案记录失败')
  }
}

// 打开录入对话框
const openAddDialog = () => {
  isAddDialogOpen.value = true
}

// 关闭录入对框
const closeAddDialog = () => {
  newRecord.value = {
    files: []
  }
  isEditing.value = false
  isAddDialogOpen.value = false
}
const fullscreenLoading = ref(false)
const importHeaders = ref([])
const importData = ref([])
const handleRISK_HAS = (event) => {
  newRecord.value.files[0] = []
  const files = Array.from(event.target.files)
  newRecord.value.files[0] = files[0]
}
const handleRECORDMATERIAL = (event) => {
  newRecord.value.files[1] = []
  const files = Array.from(event.target.files)
  newRecord.value.files[1] = files[0]
}
const handlePLANFILE = (event) => {
  newRecord.value.files[2] = []
  const files = Array.from(event.target.files)
  newRecord.value.files[2] = files[0]
}
// 添加新预案
const addNewPlan = async () => {
  if (checkval(['EMERGENCE_PLAN_ID',
    'PARK_CODE',
    'COMPANY_CODE',
    'AREA_CODE',
    'EMERGENCE_PLAN_NAME',
    'EMERGENCE_PLAN_TYPE',
    'EMERGENCE_PLAN_LEVEL',
    'PLAN_REVIEW_DATE',
    'PLAN_REVIEW_COMMENTS',
    'RECORD_DEPART',
    'PUBLISHED_RECENTLY_DATE',
    'PUBLISHED_RECENTLY_DATE',
    'RECORDED_RECENTLY_DATE',], '预案管理', newRecord.value)) {
    return
  }








  try {
    const formData = new FormData()
    for (const key in newRecord.value) {
      if (key !== 'files') {
        formData.append(key, newRecord.value[key])
      }
    }
    if (newRecord.value?.files) {
      newRecord.value.files.forEach((file, index) => {
        formData.append(`files[${index}]`, file)
      })
    }
    if (!isEditing.value) {
      const response = await axios.post(apiBaseUrl.value, formData, {
        headers: { 'Content-Type': 'multipart/form-data' }
      })
      alert('创建预案成功')
    } else {
      const response = await axios.put(apiBaseUrl.value + '/' + newRecord.value.ID, formData, {
        headers: { 'Content-Type': 'multipart/form-data' }
      })
      alert('编辑预案成功')
    }

    closeAddDialog()
    await searchPlans()
  } catch (error) {
    console.error('创建预案记录失败:', error)
    alert('创建预案记录失败: ' + (error.response?.data?.message || error.message))
  }
}



// 重置搜索
const resetSearch = () => {
  search.value = {
    plan_code: '',
    plan_name: '',
    plan_type: ''
  }
  searchPlans()
}

// 删除选中的预案
const deleteSelected = async () => {
  if (selectedIds.value.length === 0) {
    alert('请选择要删除的记录')
    return
  }
  if (confirm(`确定要删除选中的 ${selectedIds.value.length} 条记录吗？`)) {
    try {
      await Promise.all(selectedIds.value.map(async item => {
        axios.delete(`${apiBaseUrl.value}/${item.ID}`)
      }
      ))
      alert('删除成功')
      selectedIds.value = []
      table.value.clearSelection()
      await searchPlans()
    } catch (error) {
      console.error('删除记录失败:', error)
      alert('删除记录失败: ' + (error.response?.data?.message || error.message))
    }
  }
}


// 打开导入对话框
const openImportDialog = () => {
  isImportDialogOpen.value = true
  console.log('Import dialog opened') // 添加日志
}

// 关闭导入对话框
const closeImportDialog = () => {
  isImportDialogOpen.value = false
  importFile.value = null
  console.log('Import dialog closed') // 添加日志
}


// 文件上传处理
const handleFileUpload = (event) => {
  importFile.value = event.target.files[0]
  console.log('File selected:', importFile.value?.name) // 添加日志
}
const confirmImport = async () => {
  if (!importFile.value) {
    alert('请选择要导入的文件')
    return
  }
  const formData = new FormData()
  formData.append('file', importFile.value)
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  try {
    const response = await axios.post(`${apiBaseUrl.value}/import`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    loading.close()
    alert('导入成功')
    closeImportDialog()
    searchPlans()
  } catch (error) {
    loading.close()
    console.error('导入失败:', error)
    alert('导入失败: ' + (error.response?.data?.message || error.message))
  }

}





// 查看预案详情
const viewDetails = async (item) => {

  selectedItem.value = { ...item }

  isViewDialogOpen.value = true

}

// 关闭查看详情对话框
const closeViewDialog = () => {
  isViewDialogOpen.value = false
  selectedItem.value = {}
}

// 编辑预案
const openEditDialog = (item) => {
  for (const key in item) {
    if (/DATE/.test(key) && key != 'UPDATE_BY') {
      item[key] = dayjs(item[key]).format('YYYY-MM-DD')
    }
  }
  item.PLAN_REVIEWED_STATE = String(item.PLAN_REVIEWED_STATE)
  item.RISK_HAS_TOLD_YES_OR_NO = String(item.RISK_HAS_TOLD_YES_OR_NO)
  newRecord.value = { ...item }
  newRecord.value.files = []
  isEditing.value = true
  isAddDialogOpen.value = true
}


const updatePlan = async () => {
  try {
    const response = await axios.put(`${apiBaseUrl.value}/${selectedItem.value.id}`, selectedItem.value)
    alert(response.data.message || '预案更新成功')

    await searchPlans()
  } catch (error) {
    console.error('更新预案记录失败:', error)
    alert('更新预案记录失败: ' + (error.response?.data?.message || error.message))
  }
}

// 发布预案
const publishPlan = async (id) => {
  try {
    const response = await axios.put(`${apiBaseUrl.value}/${id}`, { status: '已发布' })
    alert(response.data.message || '预案发布成功')
    await searchPlans()
  } catch (error) {
    console.error('发布预案失败:', error)
    alert('发布预案失败: ' + (error.response?.data?.message || error.message))
  }
}

// 删除预案
const deletePlan = async (id) => {
  if (confirm('确定要删除这条预案记录吗？')) {
    try {
      const response = await axios.delete(`${apiBaseUrl.value}/${id}`)
      alert(response.data.message || '预案删除成功')
      await searchPlans()
    } catch (error) {
      console.error('删除预案记录失败:', error)
      alert('删除预案记录失败: ' + (error.response?.data?.message || error.message))
    }
  }
}

// 生命周期钩子
onMounted(() => {
  searchPlans()
})
const headerCellStyle = {
  height: '30px', // 设置表头高度
  lineHeight: '30px', // 设置行高以垂直居中
  backgroundColor: '#f2f2f2', // 可选：设置背景颜色
  // fontSize: '16px', // 可选：设置字体大小
}
</script>

<style scoped>
/* 移除所有现有的样式 */
</style>
